//app.js
const api = require('./utils/api.js');

App({
  onLaunch: function() {
    // 检查是否已登录
    let openid = wx.getStorageSync('openid');
    let userId = wx.getStorageSync('userId');

    if (!openid || !userId) {
      // 未登录，跳转到登录页
      wx.redirectTo({
        url: '/pages/login/login',
        fail: (err) => {
          console.error('跳转登录页失败:', err);
        }
      });
    } else {
      console.log('已登录，openid:', openid, 'userId:', userId);
    }

    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })
  },

  // 微信登录
  wxLogin: function() {
    wx.showLoading({
      title: '登录中...',
      mask: true
    });

    wx.login({
      success: (res) => {
        if (res.code) {
          // 发送 code 到后端获取 openid
          wx.request({
            url: api.wxLogin({ code: res.code }),
            method: 'GET',
            success: (response) => {
              wx.hideLoading();
              
              if (response.data.success) {
                const { data, isNewUser } = response.data;
                
                // 保存 openid 和 userId
                wx.setStorageSync('openid', data.openid);
                wx.setStorageSync('userId', data._id);
                
                console.log('登录成功！');
                console.log('openid:', data.openid);
                console.log('userId:', data._id);
                console.log('是否新用户:', isNewUser);

                // 如果是新用户，可以引导用户完善信息
                if (isNewUser) {
                  wx.showToast({
                    title: '欢迎新用户！',
                    icon: 'success',
                    duration: 2000
                  });
                }
              } else {
                console.error('登录失败:', response.data.message);
                wx.showToast({
                  title: response.data.message || '登录失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            },
            fail: (err) => {
              wx.hideLoading();
              console.error('登录请求失败:', err);
              
              // 登录失败，使用测试账号降级处理
              console.log('使用测试账号...');
              const testOpenid = 'openid_user_test';
              wx.setStorageSync('openid', testOpenid);
              wx.setStorageSync('userId', 'test_user_id');
              
              wx.showToast({
                title: '已使用测试账号',
                icon: 'none',
                duration: 2000
              });
            }
          });
        } else {
          wx.hideLoading();
          console.error('获取code失败:', res.errMsg);
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('wx.login失败:', err);
      }
    });
  },
  globalData: {
    ColorList: [{
      title: '嫣红',
      name: 'red',
      color: '#e54d42'
    },
      {
        title: '桔橙',
        name: 'orange',
        color: '#f37b1d'
      },
      {
        title: '明黄',
        name: 'yellow',
        color: '#fbbd08'
      },
      {
        title: '橄榄',
        name: 'olive',
        color: '#8dc63f'
      },
      {
        title: '森绿',
        name: 'green',
        color: '#39b54a'
      },
      {
        title: '天青',
        name: 'cyan',
        color: '#1cbbb4'
      },
      {
        title: '海蓝',
        name: 'blue',
        color: '#0081ff'
      },
      {
        title: '姹紫',
        name: 'purple',
        color: '#6739b6'
      },
      {
        title: '木槿',
        name: 'mauve',
        color: '#9c26b0'
      },
      {
        title: '桃粉',
        name: 'pink',
        color: '#e03997'
      },
      {
        title: '棕褐',
        name: 'brown',
        color: '#a5673f'
      },
      {
        title: '玄灰',
        name: 'grey',
        color: '#8799a3'
      },
      {
        title: '草灰',
        name: 'gray',
        color: '#aaaaaa'
      },
      {
        title: '墨黑',
        name: 'black',
        color: '#333333'
      },
      {
        title: '雅白',
        name: 'white',
        color: '#ffffff'
      },
    ]
  }
})